package com.plus.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @description:xss攻击和sql注入过滤
 * @author: plus
 * @create: 2023-12-18 11:25
 * @Version 1.0
 **/
@Component
@ConfigurationProperties(prefix = "spring.security.xss")
@WebFilter(filterName = "xssFilter", urlPatterns = "/*")
public class XssFilterConfig implements Filter {

    /**
     * 是否启用
     */
    private static boolean enable;
    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    /**
     * 忽略xss检查的url地址
     */
    private static List<String> excludes;
    public void setExcludes(List<String> excludes) {
        this.excludes = excludes;
    }


    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;

        if(enable){
            String pathInfo = req.getPathInfo() == null ? "" : req.getPathInfo();
            //获取请求url的后两层
            String url = req.getServletPath() + pathInfo;
            //获取请求你ip后的全部路径
            String uri = req.getRequestURI();
            //注入xss过滤器实例
            XssHttpServletRequestWraper reqW = new XssHttpServletRequestWraper(req);

            //过滤掉不需要的Xss校验的地址
            for (String str : excludes) {
                if (uri.indexOf(str) >= 0) {
                    arg2.doFilter(arg0, response);
                    return;
                }
            }
            //过滤
            arg2.doFilter(reqW, response);
        }else {
            arg2.doFilter(arg0, response);
        }

    }



    @Override
    public void destroy() {
    }
    @Override
    public void init(FilterConfig filterconfig) throws ServletException {
    }
}
